package com.leesche.zcsp.node.app.v1.controller.income.accounts;

import com.leesche.zcsp.node.app.v1.controller.admin.AppAdminController;
import com.leesche.zcsp.node.app.v1.vo.AccountSummary;
import com.leesche.zcsp.node.app.v1.vo.AccountTimeVo;
import com.leesche.zcsp.node.app.v1.vo.DeviceProfitinfoVo;
import com.leesche.zcsp.node.app.v1.vo.IncomeDetail;
import com.leesche.zcsp.node.net.service.NetService;
import com.leesche.zcsp.node.utils.UtilDate;
import com.leesche.zcsp.node.utils.calculator.Calculation;
import com.leesche.zcsp.node.utils.web.mathematical.MoneyCount;
import com.leesche.zcsp.node.utils.web.messge.WebResult;
import com.leesche.zcsp.node.web.constants.Constants;
import com.leesche.zcsp.node.web.model.PubDevGiftStock;
import com.leesche.zcsp.node.web.model.PubDeviceBalance;
import com.leesche.zcsp.node.web.model.PubDevicePayDetail;
import com.leesche.zcsp.node.web.model.PubDevicePayDetailStatistics;
import com.leesche.zcsp.node.web.service.*;
import com.leesche.zcsp.node.web.service.impl.data.read.*;
import com.leesche.zcsp.node.web.vo.StatisticQueryDate;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.text.SimpleDateFormat;
import java.util.*;

import static com.leesche.zcsp.node.utils.UtilDate.*;

/**
 * Created by kaider on 2016/11/22.
 * 账目模块
 */
@Controller
@RequestMapping("/app/v1/income/accounts")
public class AppAccountsController extends AppAdminController {
    private final static Logger LOGGER = LoggerFactory.getLogger(AppAccountsController.class);

    @Autowired
    private PubDevicePayDetailStatisticsService detailStatisticsService;
    @Autowired
    private PubDeviceService deviceService;
    @Autowired
    private PubDeviceBalanceService pubDeviceBalanceService;
    @Autowired
    private PubDevicePayDetailService pubDevicePayDetailService;
    @Autowired
    private PubDevGiftStockService pubDevGiftStockService;
    @Autowired
    private NetService netService;

    /**
     * 账目列表
     *
     * @param statisticsCondition
     * @param placeCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/listView", method = RequestMethod.POST)
    public Map<String, Object> listView(
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition,
            QueryPubPlaceCondition placeCondition
    ) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
//            Long adminId = 1L;
            Long adminId = getAdminId();
            String date = getSimpleDate();
            statisticsCondition.setUserId(adminId);
            statisticsCondition.setsDate(date);
            placeCondition.setAdminId(adminId);

            PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
            map.put("detailStatisticsDto", detailStatisticsDto);
            List<PubDevicePayDetailStatisticsDto> detailStatisticsPlaces = detailStatisticsService.findListsByCondition(statisticsCondition);
            map.put("detailStatisticsPlaces", detailStatisticsPlaces);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 总收入
     *
     * @param statisticsCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/generalIncomeView", method = RequestMethod.POST)
    public Map<String, Object> generalIncomeView(
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
//            Long adminId = 1L;
            Long adminId = getAdminId();
            statisticsCondition.setUserId(adminId);
            PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
            map.put("detailStatisticsDto", detailStatisticsDto);
            List<Long> incomeDetail = detailStatisticsService.findIncomeDetail(statisticsCondition);
            map.put("incomeDetail", incomeDetail);
            List<InfoAccountDto> accountDtoList = detailStatisticsService.findInfoAccounts(statisticsCondition);
            map.put("accountDtoList", accountDtoList);
            List<InfoAccountDto> onlinePaymentList = detailStatisticsService.findOnlinePayment(statisticsCondition);
            map.put("onlinePaymentList", onlinePaymentList);
            AccountTimeVo vo = getAccountTime(statisticsCondition.getsDate());
            map.put("accountTime", vo);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 场地总收入
     *
     * @param deviceCondition
     * @param statisticsCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/placeIncomeNewView", method = RequestMethod.POST)
    public Map<String, Object> placeIncomeNewView(
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
//            Long adminId = 1L;
            Long adminId = getAdminId();
            deviceCondition.setAdminId(adminId);
            statisticsCondition.setUserId(adminId);
            PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
            map.put("detailStatisticsDto", detailStatisticsDto);
            List<Long> incomeDetail = detailStatisticsService.findIncomeDetail(statisticsCondition);
            map.put("incomeDetail", incomeDetail);
            AccountTimeVo vo = getAccountTime(statisticsCondition.getsDate());
            map.put("accountTime",vo);

            List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

            //在线设备
            List<InfoDeviceDto> online = new ArrayList<InfoDeviceDto>();
            //离线设备
            List<InfoDeviceDto> offline = new ArrayList<InfoDeviceDto>();
            //禁用设备
            List<InfoDeviceDto> disabled = new ArrayList<InfoDeviceDto>();
            //故障设备
            List<InfoDeviceDto> fault = new ArrayList<InfoDeviceDto>();
            if(deviceList.size()>0){
                Map<String, String> deviceOnlines = netService.isOnlineBatch(this.getDeviceNames(deviceList));
                for(InfoDeviceDto dto : deviceList) {
                    if (deviceOnlines.get(dto.getImme()) != null && deviceOnlines.get(dto.getImme()).equalsIgnoreCase("ONLINE")) {
                        dto.setIsOnline(1);
                    } else {
                        dto.setIsOnline(2);
                    }
                    if (dto.getIsOnline().equals(1) && dto.getState().equals(2)) {
                        disabled.add(dto);
                    } else if (dto.getIsOnline().equals(1)) {
                        online.add(dto);
                    } else if (dto.getIsOnline().equals(2)) {
                        offline.add(dto);
                    } else {
                        fault.add(dto);
                    }
                }
            }
            map.put("online", online);
            map.put("offline", offline);
            map.put("disabled", disabled);
            map.put("fault", fault);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * 场地总收入
     *
     * @param deviceCondition
     * @param statisticsCondition
     * @return
     */
    @ResponseBody
    @RequestMapping(value = "/placeIncomeView", method = RequestMethod.POST)
    public Map<String, Object> placeIncomeView(
            QueryPubDeviceCondition deviceCondition,
            QueryPubDevicePayDetailStatisticsCondition statisticsCondition
    ) {
        try {
            Map<String, Object> map = new HashMap<String, Object>();
//            Long adminId = 1L;
            Long adminId = getAdminId();
            deviceCondition.setAdminId(adminId);
            statisticsCondition.setUserId(adminId);
            PubDevicePayDetailStatisticsDto detailStatisticsDto = detailStatisticsService.findByCondition(statisticsCondition);
            map.put("detailStatisticsDto", detailStatisticsDto);
            List<Long> incomeDetail = detailStatisticsService.findIncomeDetail(statisticsCondition);
            map.put("incomeDetail", incomeDetail);

            List<InfoDeviceDto> deviceList = deviceService.findDeviceList(deviceCondition);

            //礼品机
            List<InfoDeviceDto> giftList = new ArrayList<InfoDeviceDto>();
            //兑币机
            List<InfoDeviceDto> currencyList = new ArrayList<InfoDeviceDto>();
            //娃娃机
            List<InfoDeviceDto> dollList = new ArrayList<InfoDeviceDto>();
            //礼品兑换机
            List<InfoDeviceDto> giftExchangeList = new ArrayList<InfoDeviceDto>();

            for (InfoDeviceDto deviceDto : deviceList) {
                switch (deviceDto.getDeviceTypeId().intValue()) {
                    //礼品
                    case 1:
                        giftList.add(deviceDto);
                        break;
                    //兑币
                    case 2:
                        currencyList.add(deviceDto);
                        break;
                    //娃娃
                    case 3:
                        dollList.add(deviceDto);
                        break;
                    //礼品兑换
                    case 4:
                        giftExchangeList.add(deviceDto);
                        break;
                    default:
                        break;
                }
            }

            map.put("currencyList", currencyList);
            map.put("dollList", dollList);
            map.put("giftList", giftList);
            map.put("giftExchangeList", giftExchangeList);
            AccountTimeVo vo = getAccountTime(statisticsCondition.getsDate());
            map.put("accountTime", vo);
            return WebResult.success().put("data", map).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(e).toMap();
        }
    }

    /**
     * @param deviceSerial  设备序号
     * @param statisticDate 查询时间（如果为空表示“今天”，时间格式为：yyyy-MM-dd）
     * @return 用户场地下的设备今天或历史上某一天的账目信息
     * @Title: showThatDayAccount
     * @Description: TODO(获取设备某天的账目汇总)
     * @author Jerry
     * @date 2016-10-31 03:13:04
     */
    @ResponseBody
    @RequestMapping(value = "thatdayaccount", method = RequestMethod.POST)
    public Map<String, Object> showThatDayAccount(@RequestParam Long placeSerial, @RequestParam Long deviceSerial, @RequestParam String statisticDate) {
        AccountSummary as = null;
        try {

            if (statisticDate == null || "".equals(statisticDate)) {
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
                statisticDate = dateFormat.format(new Date());
            }

            as = new AccountSummary(deviceSerial, statisticDate);

            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setPlaceId(placeSerial);
            condition.setDeviceId(deviceSerial);
            condition.setsDate(statisticDate);
            condition.setQueryAll(true);
            List<PubDevicePayDetailStatistics> statistics = detailStatisticsService.findDeviceIncomeAccount(condition);
            if (statistics != null && statistics.size() > 0) {
                PubDevicePayDetailStatistics statistic = statistics.get(0);
                if (statistic != null) {
                    /*获取礼品库存信息*/
                    QueryPubDevGiftStockCondition giftStockCondition = new QueryPubDevGiftStockCondition();
                    giftStockCondition.setDeviceId(deviceSerial);
                    PubDevGiftStock pubDevGiftStock = pubDevGiftStockService.findGiftStockByCondition(giftStockCondition);

                    as.inventoryCashQuantity(statistic.getOnebalance(), statistic.getFivebalance(), statistic.getTenbalance(), statistic.getTwentybalance(), statistic.getFiftybalance(), statistic.getHundredbalance());
                    as.inventoryIncome(statistic.getBillmoney(), statistic.getCoinmoney(), statistic.getWechatmoney(), statistic.getAlipaymoney());
                    as.inventoryNotIncome(statistic.getIntdata1(), statistic.getGamecoinbalnce(), statistic.getGiftbalance(), statistic.getCoinbalance(), pubDevGiftStock == null ? 0 : pubDevGiftStock.getGiftqty());

                }
            } else {
                as.toZero();
                return WebResult.success().put("data", as).toMap();
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            if (as == null) {
                as = new AccountSummary(deviceSerial, statisticDate);
            }
            as.toZero();
        } finally {
            return WebResult.success().put("data", as).toMap();
        }
    }

    /**
     * @param deviceSerial 设备ID
     * @param queryDate    查询日期(日期格式为:yyyy-MM-dd)
     * @param moreindex    更多下标
     * @return 某一天中的设备下的某一批详细的流水账
     * @Title: showThatDayDetailsMore
     * @Description: TODO(分批获取某天，设备的详细流水账)
     * @author Jerry Chan
     * @date 2016-11-07 04:03:47
     */
    @ResponseBody
    @RequestMapping(value = "detailsmore", method = RequestMethod.POST)
    public Map<String, Object> showThatDayDetailsMore(final @RequestParam Long placeSerial, final @RequestParam Long deviceSerial, final @RequestParam String queryDate, @RequestParam Integer moreindex, @RequestParam Integer rows, Integer paytype) {
        try {

            QueryPubDevicePayDetailCondition condition = new QueryPubDevicePayDetailCondition();
            condition.setPage(moreindex == null ? 1 : moreindex);
            condition.setRows(rows == null ? 5 : rows);
            condition.setUserId(getAdminId());
            condition.setPlaceid(placeSerial);
            condition.setDeviceid(deviceSerial);
            condition.setReportTime(queryDate);

            if (paytype != null && paytype != 0) {
                if(paytype == 15){
                    condition.setQueryBill(true);
                }else{
                    condition.setPayType(paytype);
                }
            }

            List<PubDevicePayDetail> pubDevicePayDetails = pubDevicePayDetailService.findPayDetailByDeviceidAndUploadTime(condition);
            if (pubDevicePayDetails == null || pubDevicePayDetails.size() <= 0) {
                return WebResult.failure("已经没有更多的数据了").toMap();
            }

            IncomeDetail detail = new IncomeDetail(deviceSerial, queryDate, moreindex, new ArrayList<IncomeDetail.IncomeItem>());
            for (PubDevicePayDetail pubDevicePayDetail : pubDevicePayDetails) {
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");

                Integer index = pubDevicePayDetail.getPaytype();
                IncomeDetail.IncomeItem incomeItem = detail.new IncomeItem(pubDevicePayDetail.getDetailid(), Constants.AppDetailTitle.getText(pubDevicePayDetail.getPaytype()), Constants.AppDetailContent.getText(index), sdf.format(pubDevicePayDetail.getUploadtime()));
                incomeItem.setIncomeState(pubDevicePayDetail.getQuantity());//交易流水状态

                this.incomeContentReplace(pubDevicePayDetail, incomeItem);

                detail.getIncomeItems().add(incomeItem);
            }
            //判断是否是第一次，当第一次时则获取数据总条数
            if (condition.getPage() == 0) {
                detail.setMaxIndex(pubDevicePayDetailService.findPayDetailCount(condition));
            }

            return WebResult.success().put("data", detail).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param deviceSerial 设备的序列号（id）
     * @Title: showAccountDates
     * @Description: TODO(获取具体设备产生账目的历史时间)
     * @author Jerry
     * @date 2016-11-03 01:37:57
     */
    @ResponseBody
    @RequestMapping(value = "accountdates", method = RequestMethod.POST)
    public Map<String, Object> showAccountDates(@RequestParam Long placeSerial, @RequestParam Long deviceSerial) {
        try {
            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setPlaceId(placeSerial);
            condition.setDeviceId(deviceSerial);
            condition.setQueryAll(true);
            List<PubDevicePayDetailStatistics> statistics = detailStatisticsService.findDeviceIncomeAccount(condition);

            if (statistics == null || statistics.size() <= 0) {
                return WebResult.failure("设备未产生账目数据").toMap();
            }

            List<StatisticQueryDate> queryDates = new ArrayList<StatisticQueryDate>();
            for (PubDevicePayDetailStatistics statistic : statistics) {
                StatisticQueryDate queryDate = new StatisticQueryDate(statistic.getStatisticsid(), statistic.getUserid(), statistic.getPlaceid(), statistic.getDeviceid(), statistic.getSdate());
                queryDates.add(queryDate);
            }
            return WebResult.success().put("data", queryDates).toMap();
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return WebResult.failure(e.getMessage()).toMap();
        }
    }

    /**
     * @param deviceSerial  设备ID
     * @param thisBalanceid 本次清零结帐的id
     * @Title: showFrequencyAccount
     * @Description: TODO(根据设备的序列号和结帐清零的ID，获取当次设备的清零结帐的信息[thisBalanceid 为空表示第一次请求，返回该设备历史中最近一次清零结帐信息])
     * @author Jerry
     * @date 2016-11-03 11:01:34
     */
    @ResponseBody
    @RequestMapping(value = "frequencyaccount", method = RequestMethod.POST)
    public Map<String, Object> showFrequencyAccount(@RequestParam Long deviceSerial, @RequestParam Long thisBalanceid) {
        AccountSummary as = new AccountSummary(deviceSerial);
        try {
            QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
            condition.setUserid(getAdminId());
            condition.setDeviceid(deviceSerial);
            condition.setQueryAll(true);
            if (thisBalanceid != null && thisBalanceid > 0) {
                condition.setBalanceid(thisBalanceid);
            }

            PubDeviceBalance balance = this.pubDeviceBalanceService.findBalanceByDeviceid(condition);
            //List<PubDeviceBalance> deviceBalances = pubDeviceBalanceService.findFrequencyStatisticByDeviceid(condition);
            if (balance != null) {
                as.inventoryCashQuantity(balance.getOnebalance(), balance.getFilebalance(), balance.getTenbalance(), balance.getTwentybalance(), balance.getFiftybalance(), balance.getHundredbalance());
                Long billbalance = (balance.getOnebalance() * 1) + (balance.getFilebalance() * 5) + (balance.getTenbalance() * 10) + (balance.getTwentybalance() * 20) + (balance.getFiftybalance() * 50) + (balance.getHundredbalance() * 100);
                as.inventoryIncome(billbalance, balance.getCoinbalance(), balance.getWechatbalance(), balance.getAlipaybalance());
                SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
                as.setCreateDate(dateFormat.format(balance.getBalancetime()));
            /*获取礼品库存信息*/
                QueryPubDevGiftStockCondition giftStockCondition = new QueryPubDevGiftStockCondition();
                giftStockCondition.setDeviceId(deviceSerial);
                PubDevGiftStock pubDevGiftStock = pubDevGiftStockService.findGiftStockByCondition(giftStockCondition);
                as.inventoryNotIncome(Integer.parseInt(String.valueOf(balance.getGamecoinbu())), balance.getGamecoin(), balance.getGift(), balance.getGamecoinout(), pubDevGiftStock == null ? 0 : pubDevGiftStock.getGiftqty());
                return WebResult.success().put("data", as).toMap();
            } else {
                as.toZero();
                return WebResult.failure("该设备尚未结帐").toMap();
            }

        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            if (as == null) {
                as = new AccountSummary(deviceSerial);
                as.toZero();
            }
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @param deviceSerial 设备序列号（ID）
     * @Title: showFrequencyAccount
     * @Description: TODO(获取场地下具体设备的所有结帐清零ID集合)
     * @author Jerry
     * @date 2016-11-03 11:01:34
     */
    @ResponseBody
    @RequestMapping(value = "findfrequencyIDlist", method = RequestMethod.POST)
    public Map<String, Object> showFrequencyStatisticids(@RequestParam Long deviceSerial) {
        QueryPubDeviceBalanceCondition condition = new QueryPubDeviceBalanceCondition();
        condition.setUserid(getAdminId());
        condition.setDeviceid(deviceSerial);
        condition.setQueryAll(true);
        List<PubDeviceBalance> deviceBalances = pubDeviceBalanceService.findBalanceidsByDeviceid(condition);

        //List<PubDeviceBalance> deviceBalances = pubDeviceBalanceService.findFrequencyStatisticByDeviceid(condition);
        if (deviceBalances != null && deviceBalances.size() > 0) {

            Long[] ids = new Long[deviceBalances.size()];
            for (int i = 0; i < deviceBalances.size(); i++) {
                ids[i] = deviceBalances.get(i).getBalanceid();
            }

            Map<String, Object> idlist = new HashMap<String, Object>();
            idlist.put("lasttime", deviceBalances.size());
            idlist.put("balanceids", ids);
            return WebResult.success().put("data", idlist).toMap();
        } else {
            return WebResult.failure("该设备尚未结帐").toMap();
        }
    }

    /**
     * @param : deviceSerial 设备序列号
     * @Title: showTotalAccount(@RequestParam Long deviceSerial)
     * @Description: TODO(获取设备的总帐)
     * @author Jerry Chan
     * @date 2016/11/26 1:42
     */
    @ResponseBody
    @RequestMapping(value = "totalaccount", method = RequestMethod.POST)
    public Map<String, Object> showTotalAccount(@RequestParam Long placeSerial, @RequestParam Long deviceSerial) {
        try {
            //封装查询对象
            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setDeviceId(deviceSerial);
            condition.setPlaceId(placeSerial);
            condition.setQueryAll(true);
            //获取所有历史账目信息或所有结帐清零信息
            List<PubDevicePayDetailStatistics> statistics = detailStatisticsService.findDeviceIncomeAccount(condition);
            //判断是否有数据：
            if (statistics != null && statistics.size() > 0) {
                //有： 1.AccountSummary as = new AccountSummary(deviceSerial);
                AccountSummary as = new AccountSummary(deviceSerial);

                long billMoney = 0;
                long coinMoney = 0;
                long wechatMoney = 0;
                long alipayMoney = 0;

                for (PubDevicePayDetailStatistics statistic : statistics) {
                    //累计各面值纸币历史账目中的数量
                    as.setOneBalance(as.getOneBalance() + statistic.getOnebalance());
                    as.setFiveBalance(as.getFiveBalance() + statistic.getFivebalance());
                    as.setTenBalance(as.getTenBalance() + statistic.getTenbalance());
                    as.setTwentyBalance(as.getTwentyBalance() + statistic.getTwentybalance());
                    as.setFifyBalance(as.getFifyBalance() + statistic.getFiftybalance());
                    as.setHundredBalance(as.getHundredBalance() + statistic.getHundredbalance());
                    //累计非金钱收益统计
                    as.setRemotelyOutGameCoinQuantity(as.getRemotelyOutGameCoinQuantity() + statistic.getIntdata1());
                    as.setGameCoinQuantity(as.getGameCoinQuantity() + statistic.getGamecoinbalnce());
                    as.setGiftSellQuantity(as.getGiftSellQuantity() + statistic.getGiftbalance());
                    as.setOutGameCoinQuantity(as.getOutGameCoinQuantity() + statistic.getCoinbalance());

                    //累计收益统计
                    billMoney = billMoney + statistic.getBillmoney();
                    coinMoney = coinMoney + statistic.getCoinmoney();
                    wechatMoney = wechatMoney + statistic.getWechatmoney();
                    alipayMoney = alipayMoney + statistic.getAlipaymoney();
                }
                as.inventoryIncome(billMoney, coinMoney, wechatMoney, alipayMoney);
                //统计礼品库存
                QueryPubDevGiftStockCondition giftStockCondition = new QueryPubDevGiftStockCondition();
                giftStockCondition.setDeviceId(deviceSerial);
                PubDevGiftStock pubDevGiftStock = pubDevGiftStockService.findGiftStockByCondition(giftStockCondition);
                as.setGiftstockQuantity(pubDevGiftStock == null ? 0 : pubDevGiftStock.getGiftqty());

                return WebResult.success().put("data", as).toMap();
            } else {
                return WebResult.failure("该设备尚未产生数据").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage());
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();

        }
    }

    /**
     * @Title: showDeviceProfitInfo()
     * @Description: TODO( 获取设备收入信息 )
     * @author Jerry Chan
     * @date 2017/2/21 17:02
     */
    @ResponseBody
    @RequestMapping(value = "deviceprofitinfo", method = RequestMethod.POST)
    private Map<String, Object> showDeviceProfitInfo(String queryDate,Long palceid) {
        try {
            List<DeviceProfitinfoVo> deviceProfitinfos = null;
            SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

            QueryPubDevicePayDetailStatisticsCondition condition = new QueryPubDevicePayDetailStatisticsCondition();
            condition.setUserId(getAdminId());
            condition.setQueryTime(queryDate == null || "".equals(queryDate) ? new Date() : dateFormat.parse(queryDate));
            condition.setPlaceId(palceid == null ? null : palceid);

            List<PubDevicePayDetailStatisticsDto> dtos = detailStatisticsService.findDeviceProfitByCondition(condition);
            if (dtos.size() > 0) {
                deviceProfitinfos = new ArrayList<DeviceProfitinfoVo>();
                for (PubDevicePayDetailStatisticsDto dto : dtos) {
                    DeviceProfitinfoVo deviceProfitinfoVo = new DeviceProfitinfoVo();
                    deviceProfitinfoVo.setProfitinfoid(dto.getStatisticsid());
                    deviceProfitinfoVo.setDeviceid(dto.getDeviceid());
                    deviceProfitinfoVo.setPlaceid(dto.getPlaceid());
                    deviceProfitinfoVo.setUserid(dto.getUserid());
                    deviceProfitinfoVo.setDevicename(dto.getDevicename());
                    deviceProfitinfoVo.setAddress(dto.getAddress());
                    deviceProfitinfoVo.setDeviceshortcode(dto.getDeviceshortcode());
                    deviceProfitinfoVo.setDtname(dto.getDtname());
                    deviceProfitinfoVo.setCoinBalnce("兑出游戏币："+dto.getCoinbalance() + "个");
                    deviceProfitinfoVo.setRemoteOutCoin("远程补币：" + dto.getIntdata1() + "个");
                    deviceProfitinfoVo.setMakeCoin("设备补币："+dto.getIntdata2() + "个");
                    deviceProfitinfoVo.setCoinMoney("硬币收入：" + Constants.DECIMAL_FORMAT.format(dto.getCoinmoney()) + "元");
                    deviceProfitinfoVo.setBillMoney("现金收入：" + Calculation.addition(dto.getBillmoney()) + "元");
                    deviceProfitinfoVo.setAlipayMoney("支付宝收入：" + Constants.DECIMAL_FORMAT.format(MoneyCount.percentageCount(dto.getAlipaymoney(), Constants.percentage)) + "元");
                    deviceProfitinfoVo.setWechatMoney("微信支付收入：" + Constants.DECIMAL_FORMAT.format(MoneyCount.percentageCount(dto.getWechatmoney(), Constants.percentage)) + "元");
                    deviceProfitinfoVo.setGameCoinBalnce("投入游戏币：" + dto.getGamecoinbalnce() + "个");
                    deviceProfitinfoVo.setGiftBalance("出礼物：" + dto.getGiftbalance() + "个");

                    deviceProfitinfos.add(deviceProfitinfoVo);
                }
                return WebResult.success().put("data", deviceProfitinfos).toMap();
            } else {
                return WebResult.failure("没有更多数据了").toMap();
            }
        } catch (Exception e) {
            LOGGER.error(e.getMessage(), e);
            return WebResult.failure(Constants.SYSTEM_ERROR_PROMPT_MSG).toMap();
        }
    }

    /**
     * @Title: incomeContentReplace(Integer choose, IncomeDetail.IncomeItem incomeItem, PubDevicePayDetail pubDevicePayDetail)
     * @Description: TODO(替换收入明细内容)
     * @author Jerry Chan
     * @date 2016/11/25 23:59
     */
    private void incomeContentReplace(PubDevicePayDetail pubDevicePayDetail, IncomeDetail.IncomeItem incomeItem) {
        Integer choose = pubDevicePayDetail.getPaytype();

        if (choose > 3 && choose < 10) {
            choose = 4;
        } else if (choose >= 10) {
            choose = 5;
        }

        switch (choose) {
            case 1: //硬币收入
                Long payTotal = Long.parseLong(pubDevicePayDetail.getCoin().toString());
                incomeItem.setIncomeContent(incomeItem.getIncomeContent().replace("number", Constants.DECIMAL_FORMAT.format(payTotal)));
                break;
            case 2: //微信支付
            case 3: //支付宝支付
                //微信支付与支付宝支付需按百分比转换金额
                Long netPayTotal = Long.parseLong(pubDevicePayDetail.getCoin().toString());
                incomeItem.setIncomeContent(incomeItem.getIncomeContent().replace("number", Constants.DECIMAL_FORMAT.format(MoneyCount.percentageCount(netPayTotal, Constants.percentage))));
                break;
            case 4: //纸币收入
                //cach元number张-￥total
                Integer cash = Constants.CashType.getCachType(pubDevicePayDetail.getPaytype());
                Integer quantity = pubDevicePayDetail.getCoin();
                String content = incomeItem.getIncomeContent();
                content = content.replace("cach", String.valueOf(cash));
                content = content.replace("number", String.valueOf(quantity));
                content = content.replace("total", Constants.DECIMAL_FORMAT.format(MoneyCount.worthCount(cash, quantity).doubleValue()));
                incomeItem.setIncomeContent(content);
                break;
            case 5:
                incomeItem.setIncomeContent(incomeItem.getIncomeContent().replace("number", String.valueOf(pubDevicePayDetail.getCoin())));
                break;
            default:
                incomeItem.setIncomeContent("未知异常,请与管理员联系");
                break;
        }
    }

    /**
     * 获取账目周时间、月时间
     *
     * @return
     */
    private AccountTimeVo getAccountTime(String date) {
        AccountTimeVo vo = new AccountTimeVo();
        String sWeek = getCurrentMonday(date, 0);
        String eWeek = getPreviousSunday(date, 0);
        String sMonth = getMinMonthDate(date, 0);
        String eMonth = getMaxMonthDate(date, 0);

        vo.setsWeek(sWeek);
        vo.seteWeek(eWeek);
        vo.setsMonth(sMonth);
        vo.seteMonth(eMonth);
        return vo;
    }

    private List<String> getDeviceNames(List<InfoDeviceDto> lists) {
        List<String> deviceNames = new ArrayList<String>();
        if (lists != null) {
            for (InfoDeviceDto infoDeviceDto : lists) {
                deviceNames.add(infoDeviceDto.getImme());
            }
        }
        return deviceNames;
    }

}
